package jst.householdmanager.activities;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import jst.householdmanager.R;
import jst.householdmanager.activities.ItemListAct.ItemListAction;
import jst.householdmanager.activities.WorkPurchaseListAct.WorkPurchaseListAction;
import jst.householdmanager.database.ItemCategoriesDataSource;
import jst.householdmanager.database.ItemsDataSource;
import jst.householdmanager.database.Items_in_ItemCategoriesDataSource;
import jst.householdmanager.database.SQLiteDataSource;
import jst.householdmanager.database.ShopsDataSource;
import jst.householdmanager.database.Shops_has_ItemsDataSource;
import jst.householdmanager.database.mysql.SyncWithMysql;
import jst.householdmanager.database.mysql.SyncWithMysql.SyncDirection;
import jst.householdmanager.database.table.ItemCategories;
import jst.householdmanager.database.table.Items;
import jst.householdmanager.database.table.Items_in_ItemCategories;
import jst.householdmanager.database.table.Shops;
import jst.householdmanager.database.table.Shops_has_Items;

import android.app.ActionBar;
import android.app.AlertDialog;
import android.app.FragmentTransaction;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class MainActivity extends FragmentActivity implements ActionBar.TabListener {

	SectionsPagerAdapter mSectionsPagerAdapter;

	private SQLiteDataSource sqliteDataSource;

	ViewPager mViewPager;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.sqliteDataSource = new SQLiteDataSource(this);
		this.sqliteDataSource.open();
		setContentView(R.layout.activity_main);

		// Set up the action bar.
		final ActionBar actionBar = getActionBar();
		actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

		mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

		mViewPager = (ViewPager) findViewById(R.id.pager);
		mViewPager.setAdapter(mSectionsPagerAdapter);

		mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
			@Override
			public void onPageSelected(int position) {
				actionBar.setSelectedNavigationItem(position);
			}
		});

		for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
			actionBar.addTab(actionBar.newTab().setText(mSectionsPagerAdapter.getPageTitle(i)).setTabListener(this));
		}
	}

	@Override
	public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
		// When the given tab is selected, switch to the corresponding page in
		// the ViewPager.
		mViewPager.setCurrentItem(tab.getPosition());
	}

	@Override
	public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
	}

	@Override
	public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
	}

	@Override
	protected void onDestroy() {
		this.sqliteDataSource.close();
		super.onDestroy();
	}

	public class SectionsPagerAdapter extends FragmentPagerAdapter {

		public SectionsPagerAdapter(FragmentManager fm) {
			super(fm);
		}

		@Override
		public Fragment getItem(int position) {
			Fragment fragment = new ListFragment();
			Bundle args = new Bundle();
			args.putInt(ListFragment.ARG_ACTION_ID, position);
			fragment.setArguments(args);
			return fragment;
		}

		@Override
		public int getCount() {
			return 3;
		}

		@Override
		public CharSequence getPageTitle(int position) {
			Locale l = Locale.getDefault();
			switch (position) {
			case 0:
				return getString(R.string.work).toUpperCase(l);
			case 1:
				return getString(R.string.data).toUpperCase(l);
			case 2:
				return getString(R.string.extra).toUpperCase(l);
			}
			return null;
		}
	}

	public static class ListFragment extends Fragment {
		public static final String ARG_ACTION_ID = "actionID";
		private int actionID;

		public ListFragment() {

		}

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
			View rootView = inflater.inflate(R.layout.fragment_main_list, container, false);

			this.actionID = getArguments().getInt(ARG_ACTION_ID);

			ListView data_list = (ListView) rootView.findViewById(R.id.frg_main_list_list);
			List<String> datamenu = new ArrayList<String>();

			switch (this.actionID) {
			case 0:
				datamenu.add(getText(R.string.fill_purchaselist).toString());
				datamenu.add(getText(R.string.shoping).toString());
				datamenu.add(getText(R.string.history).toString());
				break;
			case 1:
				datamenu.add(getText(R.string.itemcategories).toString());
				datamenu.add(getText(R.string.shops).toString());
				datamenu.add(getText(R.string.items).toString());
				break;
			case 2:
				datamenu.add(getText(R.string.synctomysql).toString());
				datamenu.add(getText(R.string.syncfrommysql).toString());
				datamenu.add(getText(R.string.create_test_data).toString());
				break;
			}

			data_list.setAdapter(new ArrayAdapter<String>(this.getActivity(), android.R.layout.simple_list_item_1, datamenu));
			data_list.setOnItemClickListener(new OnItemClickListener() {
				@Override
				public void onItemClick(AdapterView<?> parentView, View selectedView, int position, long id) {
					switch (ListFragment.this.actionID) {
					case 0:
						Intent intent;
						switch (position) {
						case 0:
							intent = new Intent(ListFragment.this.getActivity(), ItemListAct.class);
							intent.putExtra("ActionId", ItemListAction.ADD_PURCHASE);
							startActivity(intent);
							break;
						case 1:
							intent = new Intent(ListFragment.this.getActivity(), WorkPurchaseListAct.class);
							intent.putExtra("ActionId", WorkPurchaseListAction.PROCESS_PURCHASE);
							startActivity(intent);
							break;
						case 2:
							intent = new Intent(ListFragment.this.getActivity(), WorkPurchaseListAct.class);
							intent.putExtra("ActionId", WorkPurchaseListAction.SHOW_HISTORY);
							startActivity(intent);
							break;
						}
						break;
					case 1:
						switch (position) {
						case 0:
							startActivity(new Intent(ListFragment.this.getActivity(), ItemCategoryListAct.class));
							break;
						case 1:
							startActivity(new Intent(ListFragment.this.getActivity(), ShopListAct.class));
							break;
						case 2:
							startActivity(new Intent(ListFragment.this.getActivity(), ItemListAct.class));
							break;
						}
						break;
					case 2:
						switch (position) {
						case 0:
							AlertDialog.Builder builder_tomysql = new AlertDialog.Builder(ListFragment.this.getActivity());
							builder_tomysql.setTitle(getText(R.string.are_you_sure));
							builder_tomysql.setMessage(getText(R.string.synctomysql));
							// yes
							builder_tomysql.setPositiveButton(getText(R.string.yes), new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog, int which) {
									dialog.dismiss();
									ListFragment.this.callSyncWithMySQL(SyncDirection.TOMYSQL);
								}
							});
							// no
							builder_tomysql.setNegativeButton(getText(R.string.no), new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog, int which) {
									dialog.dismiss();
								}
							});
							AlertDialog alert_tomysql = builder_tomysql.create();
							alert_tomysql.show();
						case 1:
							AlertDialog.Builder builder_frommysql = new AlertDialog.Builder(ListFragment.this.getActivity());
							builder_frommysql.setTitle(getText(R.string.are_you_sure));
							builder_frommysql.setMessage(getText(R.string.syncfrommysql));
							// yes
							builder_frommysql.setPositiveButton(getText(R.string.yes), new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog, int which) {
									dialog.dismiss();
									ListFragment.this.callSyncWithMySQL(SyncDirection.FROMMYSQL);
								}
							});
							// no
							builder_frommysql.setNegativeButton(getText(R.string.no), new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog, int which) {
									dialog.dismiss();
								}
							});
							AlertDialog alert_frommysql = builder_frommysql.create();
							alert_frommysql.show();
							break;
						case 2:
							MainActivity.createTestData();
							break;
						}
						break;
					}

				}
			});
			return rootView;
		}

		private void callSyncWithMySQL(SyncDirection syncDirection) {
			String errorMsg = new SyncWithMysql(syncDirection, ListFragment.this.getActivity()).startSync();
			if (errorMsg != null)
				Toast.makeText(ListFragment.this.getActivity(), errorMsg, Toast.LENGTH_LONG).show();
		}
	}

	// create Testdata
	private static void createTestData() {
		// item categories
		ItemCategories itmCat_Lebensmittel = new ItemCategories("Lebensmittel");
		ItemCategoriesDataSource.save(itmCat_Lebensmittel);
		ItemCategories itmCat_Hygiene = new ItemCategories("Hygiene");
		ItemCategoriesDataSource.save(itmCat_Hygiene);
		ItemCategories itmCat_Sonstiges = new ItemCategories("Sonstiges");
		ItemCategoriesDataSource.save(itmCat_Sonstiges);

		// shops
		Shops shop_Aldi = new Shops("Aldi");
		ShopsDataSource.save(shop_Aldi);
		Shops shop_Lidl = new Shops("Lidl");
		ShopsDataSource.save(shop_Lidl);
		Shops shop_Rewe = new Shops("Rewe");
		ShopsDataSource.save(shop_Rewe);

		// items
		Items itm_Toastbrot = new Items("Toastbrot", "Goldentoast");
		ItemsDataSource.save(itm_Toastbrot);
		Items_in_ItemCategoriesDataSource.save(new Items_in_ItemCategories(itm_Toastbrot.getId(), itmCat_Lebensmittel.getId()));
		Shops_has_ItemsDataSource.save(new Shops_has_Items(shop_Aldi.getId(), itm_Toastbrot.getId()));
		Shops_has_ItemsDataSource.save(new Shops_has_Items(shop_Lidl.getId(), itm_Toastbrot.getId()));

		Items itm_Pfeffer = new Items("Pfeffer", "Pfeffer 100g");
		ItemsDataSource.save(itm_Pfeffer);
		Items_in_ItemCategoriesDataSource.save(new Items_in_ItemCategories(itm_Pfeffer.getId(), itmCat_Lebensmittel.getId()));
		Items_in_ItemCategoriesDataSource.save(new Items_in_ItemCategories(itm_Pfeffer.getId(), itmCat_Sonstiges.getId()));
		Shops_has_ItemsDataSource.save(new Shops_has_Items(shop_Aldi.getId(), itm_Pfeffer.getId()));
		Shops_has_ItemsDataSource.save(new Shops_has_Items(shop_Lidl.getId(), itm_Pfeffer.getId()));
		Shops_has_ItemsDataSource.save(new Shops_has_Items(shop_Rewe.getId(), itm_Pfeffer.getId()));

		Items itm_Duschgel = new Items("Duschgel", "FA Duschgel");
		ItemsDataSource.save(itm_Duschgel);
		Items_in_ItemCategoriesDataSource.save(new Items_in_ItemCategories(itm_Duschgel.getId(), itmCat_Hygiene.getId()));
		Shops_has_ItemsDataSource.save(new Shops_has_Items(shop_Aldi.getId(), itm_Duschgel.getId()));

		Items itm_Milch = new Items("Milch", "Milch 3,5% Fett");
		ItemsDataSource.save(itm_Milch);
		Items_in_ItemCategoriesDataSource.save(new Items_in_ItemCategories(itm_Milch.getId(), itmCat_Lebensmittel.getId()));
		Shops_has_ItemsDataSource.save(new Shops_has_Items(shop_Aldi.getId(), itm_Milch.getId()));
		Shops_has_ItemsDataSource.save(new Shops_has_Items(shop_Lidl.getId(), itm_Milch.getId()));
		Shops_has_ItemsDataSource.save(new Shops_has_Items(shop_Rewe.getId(), itm_Milch.getId()));

		Items itm_Magerine = new Items("Magerine", "Rama Magerine");
		ItemsDataSource.save(itm_Magerine);
		Items_in_ItemCategoriesDataSource.save(new Items_in_ItemCategories(itm_Magerine.getId(), itmCat_Lebensmittel.getId()));
		Shops_has_ItemsDataSource.save(new Shops_has_Items(shop_Aldi.getId(), itm_Magerine.getId()));
		Shops_has_ItemsDataSource.save(new Shops_has_Items(shop_Rewe.getId(), itm_Magerine.getId()));

	}
}
